package com.jzt.gateway.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jzt.gateway.model.AccountInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/07/02 15:43 <br/>
 */
@Slf4j
public class AuthUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 网关授权 token 名称
     */
    public static final String GATEWAY_AUTH_TOKEN_NAME = "gw-token";
    /**
     * 账号ID
     */
    public static final String GATEWAY_USER_AGENT_ID_NAME = "user-agent-id";
    /**
     * account
     */
    private static final String Token_Account_Info = "account";

    /**
     * 获取当前登录账号
     *
     * @return 未登录返回null
     */
    public static AccountInfo getCurrentAccount(HttpServletRequest request) {
        AccountInfo accountInfo = null;
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie == null) {
                    continue;
                }
                if (cookie.getName().equalsIgnoreCase(GATEWAY_AUTH_TOKEN_NAME) && StringUtils.isNotBlank(cookie.getValue())) {
                    accountInfo = parseToken(cookie.getValue());
                    if (accountInfo != null) {
                        break;
                    }
                }
            }
        }
        if (accountInfo == null) {
            String token = request.getHeader(GATEWAY_AUTH_TOKEN_NAME);
            if (StringUtils.isNotBlank(token)) {
                accountInfo = parseToken(token);
            }
        }
        return accountInfo;
    }

    /**
     * 判断当前请求是否已登录
     */
    public static boolean isSignIn(HttpServletRequest request) {
        return getCurrentAccount(request) != null;
    }

    private static AccountInfo parseToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String[] jws = token.split("\\.");
        if (jws.length != 3) {
            return null;
        }
        String info = jws[1];
        if (StringUtils.isBlank(info)) {
            return null;
        }
        byte[] data = EncodeDecodeUtils.decodeBase64(info);
        info = new String(data);
        try {
            LinkedHashMap<?, ?> map = MAPPER.readValue(info, LinkedHashMap.class);
            if (!map.containsKey(Token_Account_Info)) {
                return null;
            }
            if (!(map.get(Token_Account_Info) instanceof String)) {
                return null;
            }
            String accountStr = (String) map.get(Token_Account_Info);
            if (StringUtils.isBlank(accountStr)) {
                return null;
            }
            AccountInfo accountInfo = MAPPER.readValue(accountStr, AccountInfo.class);
            if (StringUtils.isBlank(accountInfo.getOneId())
                    || StringUtils.isBlank(accountInfo.getPlatform())
                    || StringUtils.isBlank(accountInfo.getUserAgentId())
                    || StringUtils.isBlank(accountInfo.getLoginName())) {
                return null;
            }
            return accountInfo;
        } catch (IOException e) {
            log.warn("读取{}失败", GATEWAY_AUTH_TOKEN_NAME, e);
        }
        return null;
    }
}
